package cn.sc.summer.auth.service.user.info;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.sc.summer.constant.model.Result;
import cn.sc.summer.constant.token.TokenConstant;
import cn.sc.summer.exception.exceptions.CommonException;
import cn.sc.summer.feign.client.SysFeignClient;
import cn.sc.summer.feign.vo.UserInfoFeignVO;
import cn.sc.summer.redis.util.RedisHelper;
import cn.sc.summer.token.po.AuthorityX;
import cn.sc.summer.token.po.SysUserInfo;
import cn.sc.summer.token.po.UserDetailX;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 类名：用户信息实现类
 *
 * @author a-xin
 * @date 2023/11/22 17:07
 */
@Slf4j
@Component
public class UserServiceImpl implements UserDetailsService {

    @Resource
    private SysFeignClient sysFeignClient;

    @Override
    public UserDetailX loadUserByUsername(String username) throws AuthenticationServiceException {

        if (StrUtil.isBlank(username)) {
            throw new CommonException("userName cannot be null!");
        }

        Result<UserInfoFeignVO> result = sysFeignClient.getUserInfoByPhone(username);
        if (ObjectUtil.isNotNull(result) && !result.isOK()) {
            throw new AuthenticationServiceException(result.getMessage());
        }

        UserInfoFeignVO userInfoFeignVO = result.getData();
        Map<Object, Object> userInfoMap = RedisHelper.hmGet(TokenConstant.USER_INFO + userInfoFeignVO.getId());
        SysUserInfo sysUserInfo = BeanUtil.toBean(userInfoMap, SysUserInfo.class);

        Set<AuthorityX> userAuthList = new HashSet<>();
        userAuthList.add(AuthorityX.getDefault());

        return UserDetailX.builder()
                .userId(userInfoFeignVO.getId())
                .phone(userInfoFeignVO.getPhone())
                .username(userInfoFeignVO.getName())
                .password(sysUserInfo.getPassWord())
                .acesskey(sysUserInfo.getAcesskey())
                .openId(sysUserInfo.getOpenId())
                .tenantId(sysUserInfo.getDataTenantId())
                .authorities(userAuthList)
                .build();
    }

}
